package com.treasure.service.task.controller;

import com.alibaba.fastjson.JSON;
import com.treasure.service.task.dto.TaskSchedulerJobDto;
import com.treasure.service.task.service.Response;
import com.treasure.service.task.service.TaskSchedulerJobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.quartz.JobKey;
import org.quartz.core.jmx.JobDataMapSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @version 1.0
 * @author panxinwen 2018/10/29 16:15
 * @Copyright © 2015 | 武汉京航科技有限公司 Email:19919866605@163.com
 * */

@Api(value = "定时任务相关", description = "银谷在线定时任务统一管理")
@RestController
public class TaskController {

    @Autowired
    private TaskSchedulerJobService taskSchedulerJobService;

    /**
     * 查询定时任务列表
     */
    @RequestMapping(value = "/queryList")
    @ApiOperation(value = "查询定时任务列表", notes = "", code = 200, produces = "")
    @ApiImplicitParams({@ApiImplicitParam(name = "pageNum", value = "当前页", required = true, dataType = "Integer", paramType = "form"),
        @ApiImplicitParam(name = "pageSize", value = "分页数", required = true, dataType = "Integer", paramType = "form")})
    public String queryList(@RequestParam(value = "pageNum") Integer pageNum, @RequestParam(value = "pageSize") Integer pageSize){
        List<TaskSchedulerJobDto> list = taskSchedulerJobService.queryALL();
        Map<String, Object> map = new HashMap<>();
        map.put("rows", list);
        map.put("total", list.size());
        return JSON.toJSONString(map);
    }

    /**
     * 查询已初始化定时任务列表
     */
    @RequestMapping(value = "/queryALInitJobList")
    @ApiOperation(value = "查询已初始化定时任务列表", notes = "", code = 200, produces = "")
    @ApiImplicitParams({@ApiImplicitParam(name = "pageNum", value = "当前页", required = true, dataType = "Integer", paramType = "form"),
        @ApiImplicitParam(name = "pageSize", value = "分页数", required = true, dataType = "Integer", paramType = "form")})
    public String queryALInitJobList(@RequestParam(value = "pageNum") Integer pageNum, @RequestParam(value = "pageSize") Integer pageSize){
        List<TaskSchedulerJobDto> list = taskSchedulerJobService.list();
        Map<String, Object> map = new HashMap<>();
        map.put("rows", list);
        map.put("total", list.size());
        return JSON.toJSONString(map);
    }

    @ApiOperation("添加或修改任务Job")
    @RequestMapping(value="add", method=RequestMethod.POST, produces = "application/json; charset=UTF-8")
    public Response add(TaskSchedulerJobDto jobDto){
        boolean  result = taskSchedulerJobService.add(jobDto);
        if(result)
            return Response.success(result);
        else
            return Response.failure();
    }

    /**
     * 启用任务
     * @param jobId
     */
    @ApiOperation("启用任务Job")
    @RequestMapping(value="updUseStatus", method=RequestMethod.POST, produces = "application/json; charset=UTF-8")
    public Response updUseStatus(Integer jobId){
        boolean  result = taskSchedulerJobService.updUseStatus(jobId);
        if(result)
            return Response.success(result);
        else
            return Response.failure();
    }

    /**
     * 禁用任务
     * @param jobId
     */
    @ApiOperation(" 禁用任务Job")
    @RequestMapping(value="updUnUseStatus", method=RequestMethod.POST, produces = "application/json; charset=UTF-8")
    public Response updUnUseStatus(Integer jobId){
        boolean  result = taskSchedulerJobService.updUnUseStatus(jobId);
        if(result)
            return Response.success(result);
        else
            return Response.failure();
    }

    @ApiOperation("更新任务Job")
    @ApiImplicitParams({
        @ApiImplicitParam(name="jobGroup",value="组名",required = true,dataType = "String",paramType="path"),
        @ApiImplicitParam(name="jobName",value="名称",required = true,dataType = "String", paramType="path")
    })
    @RequestMapping("/updStautsToUp/{jobGroup}/{jobName}")
    public Response updStautsToUp(@PathVariable String jobGroup, @PathVariable String jobName){
        boolean result = taskSchedulerJobService.updStautsToUp(jobName,jobGroup);
        if(result)
            return Response.success(result);
        else
            return Response.failure("没有执行成功");
    }

    @ApiOperation("暂停定时任务Job")
    @ApiImplicitParams({
        @ApiImplicitParam(name="jobGroup",value="组名",required = true,dataType = "String",paramType="path"),
        @ApiImplicitParam(name="jobName",value="名称",required = true,dataType = "String", paramType="path")
    })
    @RequestMapping("/pause/{jobGroup}/{jobName}")
    public Response pause(@PathVariable String jobGroup, @PathVariable String jobName){
        taskSchedulerJobService.pause(jobName,jobGroup);
        return Response.success("");
    }

    @ApiOperation("重新启用定时任务Job")
    @ApiImplicitParams({
        @ApiImplicitParam(name="jobGroup",value="组名",required = true,dataType = "String",paramType="path"),
        @ApiImplicitParam(name="jobName",value="名称",required = true,dataType = "String", paramType="path")
    })
    @RequestMapping("/resume/{jobGroup}/{jobName}")
    public Response resume(@PathVariable String jobGroup, @PathVariable String jobName){
        taskSchedulerJobService.resume(jobName,jobGroup);
        return Response.success("");
    }

    @ApiOperation("单个移除")
    @ApiImplicitParams({
        @ApiImplicitParam(name="jobGroup",value="组名",required = true,dataType = "String",paramType="path"),
        @ApiImplicitParam(name="jobName",value="名称",required = true,dataType = "String", paramType="path")
    })
    @RequestMapping("/remove/{jobGroup}/{jobName}")
    public Response remove(@PathVariable String jobGroup, @PathVariable String jobName){
        taskSchedulerJobService.remove(jobName,jobGroup);
        return Response.success("");
    }

    @ApiOperation("立即触发任务")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "jobGroup",value = "组名",required = true,dataType = "String", paramType = "path"),
        @ApiImplicitParam(name = "jobName",value = "任务名",required = true,dataType = "String", paramType = "path"),
        @ApiImplicitParam(name = "jobData",value = "额外数据",required = true,dataType = "Map<String,Object>", paramType = "body")})
    @PostMapping("/triggerNow/{jobGroup}/{jobName}")
    public Response triggerNow(@PathVariable String jobGroup, @PathVariable String jobName, @RequestBody Map<String,Object> jobData){
        try {
            boolean isExists = taskSchedulerJobService.checkExists(jobName,jobGroup);
            if(isExists){
                JobKey jobKey = new JobKey(jobName,jobGroup);
                boolean result = taskSchedulerJobService.triggerNow(jobKey,JobDataMapSupport.newJobDataMap(jobData) );
                return Response.success(result);
            }else{
                return Response.failure("group : "+jobGroup+" name:"+jobName+"-->没有执行");
            }
        }catch (Exception e){
        }
        return Response.failure();
    }
}
